<template>
  <div class="ai-chat-container">
    <!-- 左侧会话列表 -->
    <div class="chat-sidebar">
      <div class="sidebar-header">
        <el-button type="primary" @click="createNewSession" class="new-session-btn">
          <el-icon><Plus /></el-icon>
          开启新对话
        </el-button>
      </div>
      
      <div class="history-section">
        <h3 class="history-title">历史记录</h3>
        <div class="session-list">
          <div 
            v-for="session in chatSessions" 
            :key="session.id"
            :class="['session-item', { 'active': currentSessionId === session.id }]"
            @click="switchSession(session.id)"
          >
            <div class="session-content">
              <div class="session-title">{{ session.title || '未命名对话' }}</div>
              <div class="session-time">{{ formatTime(session.timestamp) }}</div>
            </div>
            <el-button 
              type="text" 
              size="small" 
              @click.stop="deleteSession(session.id)"
              class="delete-session-btn"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-main">
      <!-- 聊天内容区域 -->
      <div class="chat-messages" ref="messagesContainer">
        <div v-if="currentSession && currentSession.messages.length === 0" class="empty-messages">
          <div class="empty-icon">
            <el-icon size="64"><ChatDotRound /></el-icon>
          </div>
          <h3>开始新的对话</h3>
          <p>输入您的问题，AI 将为您提供帮助</p>
        </div>
        <div 
          v-for="(message, index) in currentSession?.messages || []" 
          :key="index"
          :class="['message-item', message.isUser ? 'user-message' : 'ai-message', { 'is-thinking': message.isThinking }]"
        >
          <div class="message-avatar">
            <el-icon v-if="message.isUser"><User /></el-icon>
            <el-icon v-else><Service /></el-icon>
          </div>
          <div class="message-content">
            <div class="message-text" v-html="formatMessage(message.content)"></div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input-area">
        <div class="input-container">
          <el-input
            v-model="question"
            type="textarea"
            :rows="1"
            placeholder="输入您的问题..."
            :disabled="isLoading"
            @keydown.enter.exact="handleSubmit"
            @keydown.enter.shift="$event.preventDefault()"
            resize="none"
            class="message-input"
            :autosize="{ minRows: 1, maxRows: 4 }"
          />
          <el-button 
            type="primary" 
            @click="handleSubmit" 
            :disabled="isLoading || !question.trim()"
            class="send-btn"
          >
            <el-icon><Position /></el-icon>
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete, Loading, ChatDotRound, User, Service, Position } from '@element-plus/icons-vue';
import request from '../utiles/request';

// 响应式数据
const question = ref('');
const chatSessions = ref([]);
const currentSessionId = ref('');
const messagesContainer = ref(null);
const isLoading = ref(false);
const abortController = ref(null);

// 当前会话
const currentSession = computed(() => {
  return chatSessions.value.find(session => session.id === currentSessionId.value);
});

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now - date;
  
  // 小于1分钟显示"刚刚"
  if (diff < 60000) {
    return '刚刚';
  }
  // 小于1小时显示"xx分钟前"
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`;
  }
  // 小于24小时显示"xx小时前"
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`;
  }
  // 其他情况显示日期时间
  return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 格式化消息内容（简单的文本处理）
const formatMessage = (content) => {
  if (!content) return '';
  // 将换行符转换为<br>
  return content.replace(/\n/g, '<br>');
};

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 创建新会话
const createNewSession = () => {
  const newSession = {
    id: Date.now().toString(),
    title: '新对话',
    timestamp: Date.now(),
    messages: []
  };
  
  chatSessions.value.unshift(newSession);
  currentSessionId.value = newSession.id;
  saveSessionsToLocalStorage();
  scrollToBottom();
};

// 切换会话
const switchSession = (sessionId) => {
  currentSessionId.value = sessionId;
  saveSessionsToLocalStorage();
  nextTick(() => {
    scrollToBottom();
  });
};

// 删除会话
const deleteSession = (sessionId) => {
  ElMessageBox.confirm('确定要删除这个会话吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = chatSessions.value.findIndex(session => session.id === sessionId);
    if (index !== -1) {
      chatSessions.value.splice(index, 1);
      
      // 如果删除的是当前会话，切换到第一个会话或创建新会话
      if (currentSessionId.value === sessionId) {
        if (chatSessions.value.length > 0) {
          currentSessionId.value = chatSessions.value[0].id;
        } else {
          createNewSession();
        }
      }
      
      saveSessionsToLocalStorage();
      ElMessage.success('会话已删除');
    }
  }).catch(() => {
    // 用户取消删除
  });
};

// 处理 GBK 编码的函数
const decodeGBK = (arrayBuffer) => {
  // 尝试使用 TextDecoder 解码
  try {
    // 首先尝试 GBK 编码
    const decoder = new TextDecoder('gbk');
    return decoder.decode(arrayBuffer);
  } catch (e) {
    try {
      // 如果不支持 GBK 编码，则尝试使用 GB2312
      const decoder = new TextDecoder('gb2312');
      return decoder.decode(arrayBuffer);
    } catch (e2) {
      try {
        // 如果不支持 GB2312 编码，则尝试使用 UTF-8
        const decoder = new TextDecoder('utf-8');
        return decoder.decode(arrayBuffer);
      } catch (e3) {
        // 最后尝试手动转换
        return String.fromCharCode.apply(null, new Uint8Array(arrayBuffer));
      }
    }
  }
};

// 处理发送消息
const handleSubmit = async () => {
  if (!question.value.trim() || isLoading.value || !currentSession.value) {
    return;
  }

  // 取消之前的请求
  if (abortController.value) {
    abortController.value.abort();
  }
  
  abortController.value = new AbortController();
  const signal = abortController.value.signal;

  // 添加用户消息
  const userMessage = {
    content: question.value.trim(),
    isUser: true,
    timestamp: Date.now()
  };
  currentSession.value.messages.push(userMessage);
  
  // 更新会话标题（如果是第一条消息）
  if (currentSession.value.messages.length === 1) {
    currentSession.value.title = userMessage.content.length > 20 
      ? userMessage.content.substring(0, 20) + '...'
      : userMessage.content;
  }
  
  // 更新会话时间戳
  currentSession.value.timestamp = Date.now();
  
  // 清空输入框并禁用
  question.value = '';
  
  // 创建一个AI消息，初始显示"AI正在思考..."
  const aiMessage = {
    content: '<span class="loading-dots">AI正在思考</span>',
    isUser: false,
    timestamp: Date.now(),
    isThinking: true
  };
  currentSession.value.messages.push(aiMessage);
  
  // 滚动到底部
  scrollToBottom();
  isLoading.value = true;

  try {
    // 使用 fetch API 处理流式响应
    const response = await fetch(`http://localhost:9090/ai/streamNotId?prompt=${encodeURIComponent(userMessage.content)}`, {
      method: 'GET',
      headers: {
        'Accept': 'text/html;charset=gbk',
        'Authorization': `${localStorage.getItem('token')}`
      },
      signal
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    if (!response.body) {
      throw new Error('ReadableStream not supported in this browser.');
    }

    // 清除思考状态
    delete aiMessage.isThinking;
    aiMessage.content = '';
    
    const reader = response.body.getReader();
    let accumulatedContent = ''; // 累积内容用于流式显示
    
    try {
      while (true) {
        const { done, value } = await reader.read();
        
        if (done) {
          break;
        }
        
        // 解码当前块
        const chunk = decodeGBK(value);
        accumulatedContent += chunk;
        
        // 逐字显示累积的内容，创建打字机效果
        let index = 0;
        const typeInterval = setInterval(() => {
          if (index < accumulatedContent.length) {
            aiMessage.content = accumulatedContent.substring(0, index + 1);
            index++;
            scrollToBottom();
          } else {
            clearInterval(typeInterval);
          }
        }, 20);
      }
    } catch (decodeError) {
      console.error('解码错误:', decodeError);
      aiMessage.content += '\n[解码错误]';
    } finally {
      reader.releaseLock();
    }

    // 保存会话到本地存储
    saveSessionsToLocalStorage();
    
    ElMessage.success('对话完成');
  } catch (error) {
    // 忽略中止错误
    if (error.name !== 'AbortError' && error.code !== 'ERR_CANCELED') {
      ElMessage.error(`请求失败：${error.message || '未知错误'}`);
      
      // 更新错误消息
      if (aiMessage.content === '' || aiMessage.content === '<span class="loading-dots">AI正在思考</span>') {
        aiMessage.content = `抱歉，请求失败：${error.message || '未知错误'}`;
      } else {
        aiMessage.content += `\n\n抱歉，请求失败：${error.message || '未知错误'}`;
      }
      aiMessage.isError = true;
      
      saveSessionsToLocalStorage();
    }
  } finally {
    isLoading.value = false;
    scrollToBottom();
  }
};

// 保存会话到本地存储
const saveSessionsToLocalStorage = () => {
  try {
    localStorage.setItem('aiChatSessions', JSON.stringify(chatSessions.value));
  } catch (error) {
    console.error('保存会话失败：', error);
  }
};

// 从本地存储加载会话
const loadSessionsFromLocalStorage = () => {
  try {
    const savedSessions = localStorage.getItem('aiChatSessions');
    if (savedSessions) {
      const parsedSessions = JSON.parse(savedSessions);
      chatSessions.value = Array.isArray(parsedSessions) ? parsedSessions : [];
      
      // 如果有会话，切换到最后一个会话
      if (chatSessions.value.length > 0) {
        currentSessionId.value = chatSessions.value[0].id;
      } else {
        // 否则创建一个新会话
        createNewSession();
      }
    } else {
      // 没有保存的会话，创建一个新会话
      createNewSession();
    }
  } catch (error) {
    console.error('加载会话失败：', error);
    createNewSession();
  }
};

// 组件挂载时
onMounted(() => {
  loadSessionsFromLocalStorage();
});

// 组件卸载前
onBeforeUnmount(() => {
  // 取消所有请求
  if (abortController.value) {
    abortController.value.abort();
  }
});
</script>

<style scoped>
.ai-chat-container {
  display: flex;
  height: 100vh;
  background: #ffffff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

/* 左侧会话列表 */
.chat-sidebar {
  width: 280px;
  background: #f8fafc;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.new-session-btn {
  width: 100%;
  height: 44px;
  border-radius: 12px;
  background: #3b82f6;
  border: none;
  color: white;
  font-weight: 600;
  font-size: 14px;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(59, 130, 246, 0.2);
}

.new-session-btn:hover {
  background: #2563eb;
  box-shadow: 0 4px 8px rgba(59, 130, 246, 0.3);
}

.history-section {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.history-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 16px 0;
}

.session-list {
  flex: 1;
  overflow-y: auto;
}

.session-item {
  padding: 12px 16px;
  margin-bottom: 8px;
  border-radius: 12px;
  cursor: pointer;
  position: relative;
  transition: all 0.2s ease;
  background: #ffffff;
  border: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.session-item:hover {
  background: #f3f4f6;
  border-color: #d1d5db;
}

.session-item.active {
  background: #3b82f6;
  color: white;
  border-color: #3b82f6;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.2);
}

.session-content {
  flex: 1;
  min-width: 0;
}

.session-title {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #374151;
}

.session-item.active .session-title {
  color: white;
}

.session-time {
  font-size: 12px;
  color: #9ca3af;
}

.session-item.active .session-time {
  color: rgba(255, 255, 255, 0.8);
}

.delete-session-btn {
  opacity: 0;
  transition: all 0.2s ease;
  color: #ef4444;
  padding: 4px;
}

.session-item:hover .delete-session-btn {
  opacity: 1;
}

.session-item.active .delete-session-btn {
  color: rgba(255, 255, 255, 0.8);
}

/* 右侧聊天区域 */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  padding: 24px 48px;
  overflow-y: auto;
  background: #ffffff;
  min-height: 0;
  max-height: calc(100vh - 200px);
}

.empty-messages {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.empty-icon {
  color: #d1d5db;
  margin-bottom: 16px;
}

.empty-messages h3 {
  font-size: 20px;
  font-weight: 600;
  color: #374151;
  margin: 0 0 8px 0;
}

.empty-messages p {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.message-item {
  display: flex;
  margin-bottom: 24px;
  align-items: flex-start;
}

.message-item.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #f3f4f6;
  color: #6b7280;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  margin: 0 16px;
  flex-shrink: 0;
}

.message-item.user-message .message-avatar {
  background: #3b82f6;
  color: white;
}

.message-content {
  flex: 1;
  max-width: calc(100% - 72px);
  min-width: 0;
}

.message-item.user-message .message-content {
  text-align: right;
}

.message-text {
  background: #f8fafc;
  padding: 16px 20px;
  border-radius: 16px;
  font-size: 14px;
  line-height: 1.6;
  word-wrap: break-word;
  border: 1px solid #e5e7eb;
  text-align: left;
  white-space: pre-wrap;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  max-width: 100%;
}

.message-item.user-message .message-text {
  background: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.message-time {
  font-size: 12px;
  color: #9ca3af;
  margin-top: 8px;
}

.message-item.user-message .message-time {
  color: rgba(255, 255, 255, 0.7);
}

.message-item.ai-message.is-thinking .message-text {
  color: #6b7280;
  font-style: italic;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 为思考状态的消息添加加载动画效果 */
.loading-dots::after {
  content: '';
  animation: loading-dots 1.5s infinite;
}

@keyframes loading-dots {
  0% { content: ''; }
  25% { content: '.'; }
  50% { content: '..'; }
  75% { content: '...'; }
  100% { content: ''; }
}

/* 输入区域 */
.chat-input-area {
  background: #ffffff;
  border-top: 1px solid #e5e7eb;
  padding: 10px 14px;
 
  
}

.input-container {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  max-width: 100%;
  margin: 0;
  padding: 0 24px;
}

.message-input {
  flex: 1;
}

.message-input :deep(.el-textarea__inner) {
  background: #f8fafc;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 12px 16px;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
  box-shadow: none;
  transition: all 0.2s ease;
}

.message-input :deep(.el-textarea__inner):focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  background: #ffffff;
}

.send-btn {
  height: 44px;
  width: 44px;
  border-radius: 12px;
  background: #3b82f6;
  border: none;
  color: white;
  font-size: 18px;
  transition: all 0.2s ease;
  flex-shrink: 0;
  box-shadow: 0 2px 4px rgba(59, 130, 246, 0.2);
}

.send-btn:hover:not(:disabled) {
  background: #2563eb;
  box-shadow: 0 4px 8px rgba(59, 130, 246, 0.3);
}

.send-btn:disabled {
  background: #d1d5db;
  color: #9ca3af;
  cursor: not-allowed;
  box-shadow: none;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .chat-input-area {
    left: 280px;
  }
}

@media (max-width: 768px) {
  .chat-sidebar {
    width: 240px;
  }
  
  .chat-messages {
    padding: 16px 32px;
    padding-bottom: 100px;
    max-height: calc(100vh - 180px);
  }
  
  .chat-input-area {
    left: 240px;
    padding: 16px;
    max-width: calc(100vw - 240px);
  }
  
  .input-container {
    padding: 0 16px;
  }
}

@media (max-width: 480px) {
  .chat-sidebar {
    width: 200px;
  }
  
  .chat-messages {
    padding: 12px 24px;
    padding-bottom: 80px;
    max-height: calc(100vh - 160px);
  }
  
  .chat-input-area {
    left: 200px;
    padding: 12px;
    max-width: calc(100vw - 200px);
  }
  
  .input-container {
    gap: 8px;
    padding: 0 12px;
  }
  
  .send-btn {
    width: 40px;
    height: 40px;
  }
}
</style>